﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace dacli.modelos.dao
{
    public class Conexion
    {
        public SqlConnection conexion;

        public Conexion()
        {
            this.conexion = new SqlConnection(this.getConexionString());
        }

        private string getConexionString()
        {
            string strConn = ConfigurationManager.ConnectionStrings["dacli.Properties.Settings.dacliConnectionString"].ConnectionString;
            return strConn;
        }

        private SqlConnection getConexion()
        {
            return conexion;
        }
                
        public void conectar()
        {
            if (this.conexion.State != System.Data.ConnectionState.Open)
            {
                this.conexion.Open();
            }
        }

        public void cerrar()
        {
            if (this.conexion.State == System.Data.ConnectionState.Open)
            {
                this.conexion.Close();
            }
        }
        
        public long ejecutar(string sql, bool trans = false)
        {
            this.conectar();
            SqlCommand comando = conexion.CreateCommand();            
            if (sql[0] == 'i' || sql[0] == 'I')
            {
                comando.CommandText = sql + ";SELECT SCOPE_IDENTITY();";
            }
            else
            {
                comando.CommandText = sql + "";
            }
            modelos.clases.Configuraciones.log(comando.CommandText);
           long result = Convert.ToInt64( comando.ExecuteScalar());
           return result;          
        }

        public SqlDataReader consultar(String sql)
        {
            this.cerrar();
            this.conectar();
            SqlCommand comando = conexion.CreateCommand();
            comando.CommandText = sql;
            modelos.clases.Configuraciones.log(comando.CommandText);
            SqlDataReader reader  = comando.ExecuteReader();            
            return reader;
        }
        public SqlDataAdapter consultarAdapter(String sql)
        {
            this.conectar();
            SqlCommand comando = conexion.CreateCommand();
            comando.CommandText = sql;
            SqlDataAdapter adaptador = new SqlDataAdapter(comando);
            return adaptador;
        }


    }
}
